// miniprogram/pages/study/study.js
const util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    score: 0,
    percent: 0,
    btnText: '下一题',
    rightNum: 0,
    status: 0,
    idx: 0,
    length: 0,
    times: "60:00"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    console.log(options);
    let id = options.id || '';
    let uuid = options.uuid || '';
    this.setData({
      uuid
    },()=>{
      
    })
    this.onQuery();
    this.onGetOpenid();
  },
  
  onQuery: function(id){
    let that = this;
    const db = wx.cloud.database();

    db.collection('questions')
    .aggregate()
    .match({
      category: app.globalData.category._id
    })
    .sample({
      size: 10
    })
    .end()
    .then(res => {
      console.log('[数据库] [查询记录] 成功: ', res)
      let questions = res.list;
      questions.forEach((ques,idx)=>{
        ques.index = idx;
        ques.selected = false;

        let options = ques.options;
        options.forEach(option => {
          option.selected = false;
        });
        ques.options = options;
      })
      let question = questions[0];
      that.setData({
        question,
        questions,
        length: questions.length
      },()=>{
        wx.hideLoading()
        console.log(question);
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      openid: app.globalData.openid
    })
    this.timeServal(59);
    this.onGetTime();
    this.onGetUUID();
    this.queryProfile();
    
  },
  timeServal: function (t) {
    console.log(t)
    
    if (0 != t) {
      var e = t,
        a = 59,
        n = this;
        app.globalData.timeInterval = setInterval(function () {
        a < 10 ? n.setData({
          times: e + ":0" + a,
          ytimes: t - e + ":" + (59 - a)
        }) : n.setData({
          times: e + ":" + a,
          ytimes: t - e + ":" + (59 - a)
        }), --a < 0 && (e > 0 ? (a = 59, e--) : (a = 0, e = 0, n.setData({
          startTimeind: !0
        })));
      }, 1e3);

      
    } else this.setData({
      times: 0
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  generate: function(){
    return util.formatTime(new Date());
  },
  addNote: function(){
    let that = this;
    let idx = this.data.idx;
    let questions = this.data.questions;
    let question = questions[idx];
    let qid = question['_id'];
    const db = wx.cloud.database()
    db.collection('notes').add({
      data: {
        uuid: this.data.uuid,
        qid: qid,
        question: question
      },
      success: res => {
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id
        // wx.showToast({
        //   title: '新增记录成功',
        // })
        
        
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  select: function(e){
    let status = this.data.status;
    if(status == 2){
      wx.showToast({
        icon: 'none',
        title: '您已提交'
      })
      return;
    }
    console.log(e.currentTarget.dataset);
    let code = e.currentTarget.dataset.code;
    let option = JSON.parse(e.currentTarget.dataset.value);
    console.log('单选选中事件');
    console.log(option);
    let questions = this.data.questions;
    let idx = this.data.idx;
    let question = this.data.questions[idx];
    let options = question.options;
    let arr = [];
    let typecode = question.typecode;
    switch(typecode+''){
      case '01':
        options.forEach(element => {
          element.selected = false;
          if(code == element.code){
            element.selected = true;
          }
          arr.push(element);
        });
        break;
        case '02':
          options.forEach(element => {
            
            if(code == element.code){
              element.selected = !element.selected;
            }
            arr.push(element);
          });
          break;
        case '03':
          options.forEach(element => {
            element.selected = false;
            if(code == element.code){
              element.selected = true;
            }
            arr.push(element);
          });
          break;        
    }
    let codeArr = [];
    options.forEach(option=>{
      if(option.selected){
        codeArr.push(option.code)
      }
    })
    question.options = arr;
    questions[idx] = question;
    this.setData({
      code: codeArr.join(','),
      status: 1,
      question,
      options: arr,
      questions
    })
  },
  changeStatus: function(){
    let question = this.data.question;
    let options = this.data.options;
    let right = 0;

    let selected = false;
    options.forEach(option => {
      if(option.selected){
        selected = true;
      }
    })
    
    if(!selected){
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '请先选择您的答案',
        confirmText: '我知道了',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
      return;
    }

    let codeArr = [];
    options.forEach(option=>{
      if(option.selected){
        codeArr.push(option.code)
      }
    })

    console.log(codeArr.join(''));
    console.log(question.answer);
    if(codeArr.join('') == question.answer){
      right = 1;
    }
    if(right == 1){
      this.updateInfo(1,0);
      this.setData({
        rightNum: this.data.rightNum+1
      })
    }else{
      this.updateInfo(0,1);
      this.addNote();
    }
    this.setData({
      status: 2
    },()=>{
      
    })
  },
  updateInfo: function(num1,num2){
    let that = this;
    let idx = this.data.idx;
    let questions = this.data.questions;
    let question = questions[idx];
    let qid = question['_id'];

    const db = wx.cloud.database()
    const _ = db.command
    db.collection('questions').doc(qid).update({
      data: {
        // 表示指示数据库将字段自增 10
        rightnums: _.inc(num1),
        wrongnums: _.inc(num2),
        nums: _.inc(1)
      },
      success: function(res) {
        // console.log(res)
      }
    })
  },

  addLog: function(){

    let time = util.getTime(new Date());

    const db = wx.cloud.database()
    db.collection('logs').add({
      data: {
        page: 'pages/exam/exam',
        data: this.data,
        time
      }
      })
      .then(res=>{
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        // 在返回结果中会包含新创建的记录的 _id  

      })
      .catch(err=>{

      })
  },
  goResult: function(){
    this.addLog();
    let rightNum = parseInt(this.data.rightNum);
      wx.hideLoading()
      let url = '/pages/examresult/examresult?uuid='+this.data.uuid+'&length='+this.data.length+'&rightNum='+rightNum;
      wx.redirectTo({
        url: url
      })
  },
  
  generate: function(){
    return util.formatTime(new Date());
  },
  doNext: function(){
    console.log('doNext')
    let idx = this.data.idx+1;
    let questions = this.data.questions;
    let length = this.data.length;
    let percent = (idx/length)*100;
    if(length-idx == 1){
      this.setData({
        btnText: '完成'
      })
      wx.showToast({
        icon: 'none',
        title: '已经是最后一题了'
      })
    }
    if(idx == length){
      wx.showLoading({
        title: '处理中',
        mask: true
      })
      // 最后一题更新记录
      this.addHistory();
      return;
    }
    this.setData({
      percent,
      idx,
      status: 0,
      question: questions[idx]
    })

  },
  addHistory: async function(){
    let time = this.data.time;
    let score = parseInt(this.data.rightNum);


    const db = wx.cloud.database()
    const res = await db.collection('historys').where({
      _openid: this.data.openid
    }).count();
    if(res.total == 0){
      
      db.collection('historys').add({
        data: {
          _id: this.data.uuid,
          name: this.data.name,
          dept: this.data.dept,
          questions: this.data.questions,
          score,
          today: this.data.today,
          createTime: time
        }
        })
        .then(res=>{
          console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
          // 在返回结果中会包含新创建的记录的 _id  
          this.goResult();
        })
        .catch(err=>{
  
        })
    }else{
      // 已经参加过考试

      const res2 = await db.collection('historys').where({
        _openid: this.data.openid
      }).get();
      let historys = res2.data;
      let uuid = historys[0]['_id'];

      db.collection('historys').doc(uuid).update({
        data: {
          name: this.data.name,
          dept: this.data.detp,
          questions: this.data.questions,
          score,
          today: this.data.today,
          createTime: time
        }
        })
        .then(res=>{
          console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
          // 在返回结果中会包含新创建的记录的 _id  
          this.goResult();
        })
        .catch(err=>{
  
        })
    }


  },
  onGetOpenid: function() {
    let that = this;
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login]: ', res)
        app.globalData.openid = res.result.openid
        that.setData({
          openid: res.result.openid
        })
        // wx.navigateTo({
        //   url: '../userConsole/userConsole',
        // })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },
  queryProfile: function(){

    let openid = app.globalData.openid;

    let that = this;
    const db = wx.cloud.database()
    db.collection('profiles')
    .doc(openid)
    .get()
    .then((res)=>{
      console.log('[数据库] [查询记录] 成功: ', res);
      this.setData({
        name: res.data.name,
        dept: res.data.dept
      })
    })
    .catch((err)=>{
      console.log(err)
      console.error('[数据库] [查询记录] 失败：', err)
      wx.showToast({
        icon: 'none',
        title: '查询记录失败'
      })
    })
  },
  onGetTime: function(){
    let time = util.formatTime(new Date());
    wx.cloud.callFunction({
      // 云函数名称
      name: 'getTime',
      // 传给云函数的参数
      data: {
      },
    })
    .then(res => {
      console.log('[云函数] [getTime]: ', res)
      this.setData({
        today: res.result.today,
        time: res.result.time
      })
    })
    .catch((err)=>{
      console.error('[云函数] [getTime] 调用失败', err)
      wx.navigateTo({
        url: '../deployFunctions/deployFunctions',
      })
    })
    
  },

  onGetUUID: function() {
    // 调用云函数
    let that = this;
    wx.cloud.callFunction({
      name: 'getUUID',
      data: {

      }
    })
    .then(res => {
      console.log('[云函数] [getUUID]: ', res)
      this.setData({
        uuid: res.result.uuid
      },()=>{
        console.log(this.data.uuid);
      })
      
    }).catch(err => {
      console.error('[云函数] [getUUID] 调用失败', err)
      wx.navigateTo({
        url: '../deployFunctions/deployFunctions',
      })
    })
  }
})